﻿#region

using System.Text.Json;
using System.Text.Json.Serialization;
using Vin.Tool.Core.DateTimeCategory;

#endregion

namespace Vin.Tool.Core.JsonCategory.Converters;

public class LongToStringConverter : JsonConverter<long>
{
    public override long Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        if (reader.TokenType == JsonTokenType.String)
        {
            if (long.TryParse(reader.GetString(), out long value))
            {
                return value;
            }

            if (DateTime.TryParse(reader.GetString(), out DateTime date))
            {
                return date.ToTimestamp(false);
            }

            return 0;
        }
        else if (reader.TokenType == JsonTokenType.Number)
        {
            return reader.GetInt64();
        }

        throw new JsonException($"Unable to parse {typeToConvert.Name} from JSON.");
    }

    public override void Write(Utf8JsonWriter writer, long value, JsonSerializerOptions options)
    {
        if (value > int.MaxValue)
        {
            writer.WriteStringValue(value.ToString());
        }
        else
        {
            writer.WriteNumberValue(value);
        }
    }
}